<template>
    <div class="search-value-box">
        <div class="base bg-white">
            <div class="w-full">
                <div class="sv-t">
                    <div class="w-1/2">
                        <n-dropdown @select="handleSelect" trigger="hover" :options="options">
                            <n-input v-model:value="searchValue" type="text" placeholder="音乐/视频/电台/用户" clearable
                                     :on-input="inputChange" @keyup.enter="getRouterToSearchValue(searchValue)"/>
                        </n-dropdown>
                    </div>
                </div>
                <div class="sv-content">
                    <n-card :title="`搜索${route.query.keywords},找到${pageItem[currentTabName]}个${currentTabName}`"
                            style="margin-bottom: 16px;">
                        <n-tabs default-value="歌曲" justify-content="space-evenly" type="line"
                                :on-update:value="onUpdateTabs">
                            <n-tab-pane name="歌曲" tab="歌曲">
                                <div v-for="(item, index) in songs" :key="index"
                                     class="flex items-center h-16 hover:border-gray400 hover:bg-gray-100 cursor-pointer">
                                    <div class="mx-4 flex items-center">
                                        <n-icon size="20" @mouseenter="isShowPlayIconBacg(index, '#515151')"
                                                @mouseleave="isShowPlayIconBacg(index, '#999999')"
                                                @click="musicPlay(item.id)">
                                            <svg t="1628492636847" class="cursor-pointer" viewBox="0 0 1024 1024"
                                                 version="1.1"
                                                 xmlns="http://www.w3.org/2000/svg" p-id="1211" width="200"
                                                 height="200">
                                                <path
                                                    d="M512 960C264.576 960 64 759.424 64 512S264.576 64 512 64s448 200.576 448 448-200.576 448-448 448z m0-64c212.077 0 384-171.923 384-384S724.077 128 512 128 128 299.923 128 512s171.923 384 384 384z m134.51-329.505L442.78 691.96c-15.048 9.267-34.76 4.58-44.028-10.468a32 32 0 0 1-4.752-16.78V359.288c0-17.673 14.327-32 32-32a32 32 0 0 1 16.78 4.752l203.73 125.465c30.097 18.535 39.47 57.958 20.935 88.055a64 64 0 0 1-20.935 20.935z"
                                                    p-id="1212" :fill="playIconColor[index]"></path>
                                            </svg>
                                        </n-icon>
                                    </div>
                                    <div class="grid grid-cols-12 w-full">
                                        <div class="col-span-7 hover:text-red-600 hover:underline" :title="item.name"
                                             @click="songDetailPage(item.id)">
                                            {{ calString(item.name, 40) }}
                                            <span v-show="item.alias.length !== 0"
                                                  class="text-gray-400">({{ item.alias[0] }})</span>
                                        </div>
                                        <div class="col-span-2 hover:text-red-600 hover:underline"
                                             :title="item.artists[0].name"
                                             @click="getRouterToArtistInfo(item.artists[0].id)">
                                            {{ item.artists[0].name }}
                                        </div>
                                        <div class="col-span-2 hover:text-red-600 hover:underline"
                                             :title="item.album.name" @click="getRouterToAlbumList(item.album.id)">
                                            {{ calString(item.album.name, 20) }}
                                        </div>
                                        <div class="col-span-1">{{ calMSToMinAndS(item.duration) }}</div>
                                    </div>
                                </div>
                            </n-tab-pane>
                            <n-tab-pane name="歌手" tab="歌手">
                                <div class="grid grid-cols-5 gap-x-2 gap-y-4">
                                    <div v-for="(item, index) in artists" :key="index"
                                         @click="getRouterToArtistInfo(item.id)">
                                        <n-image
                                            width="150"
                                            :style="{ border: '1px solid #999999'}"
                                            :src="item.picUrl + '?param=150y150'"
                                        />
                                        <p class="hover:underline cursor-pointer" :title="item.name">
                                            {{ calString(item.name, 12) }}</p>
                                    </div>
                                </div>
                            </n-tab-pane>
                            <n-tab-pane name="专辑" tab="专辑">
                                <div class="grid grid-cols-5 gap-x-2 gap-y-4">
                                    <div v-for="(item, index) in albums" :key="index">
                                        <n-image
                                            width="150"
                                            :style="{ border: '1px solid #999999'}"
                                            :src="item.picUrl+ '?param=150y150'"
                                        />
                                        <p class="cursor-pointer hover:underline" :title="item.name">
                                            {{ calString(item.name, 15) }}</p>
                                        <p class="text-gray-400">{{ calData(item.publishTime) }}</p>
                                    </div>
                                </div>
                            </n-tab-pane>
                            <n-tab-pane name="MV" tab="MV">
                                
                                <div class="grid grid-cols-5 gap-x-2 gap-y-4">
                                    <div class="shadow-2xl cursor-pointer border hover:border-red-600"
                                         v-for="(item, index) in mvs"
                                         :key="index">
                                        <div
                                            :style="{background: `url(${item.cover}?param=240y150) no-repeat`}"
                                            style="height: 128px" :title="item.name"
                                            @click="getRouterToVideoPage(item)">
                                            <div class="flex">
                                                <p class="text-white my-auto ml-auto">{{ item.playCount }}</p>
                                            </div>
                                            <div class="h-3/4 flex items-end ml-2 transform translate-y-2">
                                                <p class="text-white">{{ calMSToMinAndS(item.duration) }}</p>
                                            </div>
                                        </div>
                                        <div class="ml-1">
                                            <p :title="item.name" class="hover:underline cursor-pointer">
                                                {{ calString(item.name, 30) }}</p>
                                            <p :title="item.artistName" class="hover:underline cursor-pointer">
                                                {{ item.artistName }}</p>
                                        </div>
                                    </div>
                                </div>
                            </n-tab-pane>
                            
                            <n-tab-pane name="video" tab="视频">
                                <div class="grid grid-cols-5 gap-x-2 gap-y-4">
                                    <div class="shadow-2xl cursor-pointer border hover:border-red-600"
                                         v-for="(item, index) in videos"
                                         :key="index">
                                        <div
                                            :style="{background: `url(${item.coverUrl}?param=240y150) no-repeat`}"
                                            style="height: 128px" :title="item.title"
                                            @click="getRouterToVideoPage(item)">
                                            <div class="flex">
                                                <p class="text-white my-auto ml-auto">{{ item.playTime }}</p>
                                            </div>
                                            <div class="h-3/4 flex items-end ml-2 transform translate-y-2">
                                                <p class="text-white">{{ calMSToMinAndS(item.durationms) }}</p>
                                            </div>
                                        </div>
                                        <div class="ml-1">
                                            <p :title="item.name" class="hover:underline cursor-pointer">
                                                {{ calString(item.title, 30) }}</p>
                                            <p :title="item.artistName" class="hover:underline cursor-pointer">
                                                {{ calString(item.creator[0].userName, 30) }}</p>
                                        </div>
                                    </div>
                                </div>
                            </n-tab-pane>
                            
                            <n-tab-pane name="歌单" tab="歌单">
                                <div v-for="(item, index) in playlists" :key="index"
                                     class="flex items-center h-16 hover:border-gray400 hover:bg-gray-100 cursor-pointer">
                                    <div class="mx-4 flex items-center">
                                        <n-icon size="20" @mouseenter="isShowPlayIconBacg(index, '#515151')"
                                                @mouseleave="isShowPlayIconBacg(index, '#999999')"
                                                @click="musicPlay(item.id, 0)">
                                            <svg t="1628492636847" class="cursor-pointer" viewBox="0 0 1024 1024"
                                                 version="1.1"
                                                 xmlns="http://www.w3.org/2000/svg" p-id="1211" width="200"
                                                 height="200">
                                                <path
                                                    d="M512 960C264.576 960 64 759.424 64 512S264.576 64 512 64s448 200.576 448 448-200.576 448-448 448z m0-64c212.077 0 384-171.923 384-384S724.077 128 512 128 128 299.923 128 512s171.923 384 384 384z m134.51-329.505L442.78 691.96c-15.048 9.267-34.76 4.58-44.028-10.468a32 32 0 0 1-4.752-16.78V359.288c0-17.673 14.327-32 32-32a32 32 0 0 1 16.78 4.752l203.73 125.465c30.097 18.535 39.47 57.958 20.935 88.055a64 64 0 0 1-20.935 20.935z"
                                                    p-id="1212" :fill="playIconColor[index]"></path>
                                            </svg>
                                        </n-icon>
                                    </div>
                                    
                                    <div class="grid grid-cols-12 w-full">
                                        <div class="col-span-7 hover:text-red-600 hover:underline" :title="item.name"
                                             @click="getListDetail(item.id)">
                                            <div class="flex items-center">
                                                <n-image width="50" :src="item.coverImgUrl + '?param=50y50'"></n-image>
                                                <span class="ml-2">{{ item.name }}</span>
                                            </div>
                                        </div>
                                        <div class="col-span-2 flex items-center">
                                            <span class="text-gray-400 mr-2">
                                                {{ item.trackCount }}首
                                            </span>
                                            <span class="hover:text-red-600 hover:underline"
                                                  @click="getRouterToUserHome(item.creator.userId)">
                                                {{ item.creator.nickname }}
                                            </span>
                                        </div>
                                        <div class="col-span-2 flex items-center">
                                            <p class="text-gray-400">收藏: {{ item.bookCount }}</p>
                                        </div>
                                        <div class="col-span-1 text-gray-400 flex items-center">收听: {{
                                                item.playCount
                                            }}
                                        </div>
                                    </div>
                                </div>
                            </n-tab-pane>
                            <n-tab-pane name="用户" tab="用户">
                                <div v-for="(item, index) in userProfiles" :key="index"
                                     class="flex items-center h-16 hover:border-gray400 hover:bg-gray-100 cursor-pointer">
                                    <div class="grid grid-cols-12 w-full">
                                        <div class="col-span-11" :title="item.name"
                                             @click="getRouterToUserHome(item.userId)">
                                            <div class="flex items-center">
                                                <n-image width="50" :src="item.avatarUrl + '?param=50y50'"></n-image>
                                                <div>
                                                    <p class="ml-2">{{ item.nickname }}</p>
                                                    <p class="ml-2 text-gray-400">{{ item.signature }}</p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="flex items-center">
                                            <n-button v-show="!item.followed" @click="followedUser(index, id, 1)">关注
                                            </n-button>
                                            <n-button type="error" v-show="item.followed"
                                                      @click="followedUser(index, id, 0)">取消关注
                                            </n-button>
                                        </div>
                                    </div>
                                </div>
                            </n-tab-pane>
                        </n-tabs>
                    </n-card>
                    
                    <div class="flex items-center justify-center my-4">
                        <n-pagination v-model:page="page" :page-count="pageCount" :on-update:page="OnPageUpdate"
                                      show-quick-jumper/>
                    </div>
                </div>
            </div>
        
        </div>
    </div>
</template>

<script>
import {
    NDropdown,
    NInput,
    useNotification,
    NCard,
    NTabs,
    NTabPane,
    NPagination,
    NIcon,
    NImage,
    NButton
} from 'naive-ui';
import {getSearchSuggest, getSearchValue} from "@/network/data/serachValue";
import {useRoute, useRouter} from "vue-router";
import {onMounted, reactive, toRefs} from "vue";
import {calMSToMinAndS, calString, calInteger, calData} from "@/util/cal";
import {getSingleMusicPlay, getSingleMusicList} from "@/util/music";
import {useStore} from "vuex";
import {getPlayListDetail} from "@/network/song/song-list";

export default {
    name: "ShowSearchValue",
    setup() {
        const router = useRouter();
        const store = useStore();
        const route = useRoute();
        const notification = useNotification();
        const valueInfo = reactive({
            searchValue: route.query.keywords,
            options: [],
            songs: [],
            artists: [],
            albums: [],
            mvs: [],
            videos: [],
            playlists: [],
            userProfiles: [],
            pageLimit: 30,
            // 播放按钮的颜色
            playIconColor: new Array(30).fill('#999999'),
        })
        // 显示加载遮罩
        const beLoading = () => {
            store.commit('setLoading', true);
        }
        const pageInfo = reactive({
            page: 1,
            pageCount: 1,
            pageItem: {
                '歌曲': 0,
                '歌手': 0,
                '专辑': 0,
                'MV': 0,
                'video': 0,
                '歌单': 0,
                '用户': 0,
            },
            currentTabName: '歌曲'
        })
        const init = () => {
            beLoading();
            getSearchValue(valueInfo.searchValue).then(res => {
                
                console.log(res);
                valueInfo.songs = res.data.result.songs;
                pageInfo.pageItem['歌曲'] = res.data.result.songCount;
                pageInfo.pageCount = calInteger(res.data.result.songCount / valueInfo.pageLimit);
            })
        }
        
        
        onMounted(() => {
            init();
        })
        // 分页按钮事件
        const OnPageUpdate = (page) => {
            pageInfo.page = page;
            if (pageInfo.currentTabName === '歌曲') {
                getSearchValue(valueInfo.searchValue, 1, (page - 1) * valueInfo.pageLimit).then(res => {
                    valueInfo.songs = res.data.result.songs;
                })
            } else if (pageInfo.currentTabName === '歌手') {
                getSearchValue(valueInfo.searchValue, 100, (page - 1) * valueInfo.pageLimit).then(res => {
                    valueInfo.artists = res.data.result.artists;
                })
            } else if (pageInfo.currentTabName === '专辑') {
                getSearchValue(valueInfo.searchValue, 10, (page - 1) * valueInfo.pageLimit).then(res => {
                    valueInfo.albums = res.data.result.albums;
                })
            } else if (pageInfo.currentTabName === 'MV') {
                getSearchValue(valueInfo.searchValue, 1004, (page - 1) * valueInfo.pageLimit).then(res => {
                    valueInfo.mvs = res.data.result.mvs;
                })
            } else if (pageInfo.currentTabName === 'video') {
                getSearchValue(valueInfo.searchValue, 1014, (page - 1) * valueInfo.pageLimit).then(res => {
                    valueInfo.videos = res.data.result.videos;
                })
            } else if (pageInfo.currentTabName === '歌单') {
                getSearchValue(valueInfo.searchValue, 1000, (page - 1) * valueInfo.pageLimit).then(res => {
                    valueInfo.playlists = res.data.result.playlists;
                })
            } else if (pageInfo.currentTabName === '用户') {
                getSearchValue(valueInfo.searchValue, 1002, (page - 1) * valueInfo.pageLimit).then(res => {
                    valueInfo.userProfiles = res.data.result.userprofiles;
                })
            }
            window.scrollTo(0, 0);
            beLoading();
        }
        
        // 音乐播放
        const musicPlay = (id, flag = 1) => {
            beLoading();
            if (flag === 1) {
                // 单曲
                getSingleMusicPlay(id);
            } else {
                // 列表播放
                let tracks = [];
                getPlayListDetail(id).then(res => {
                    tracks = res.data.playlist.tracks.slice(0, 10);
                    getSingleMusicList(tracks);
                })
            }
        }
        // 搜索建议触发事件
        const inputChange = () => {
            getSearchSuggest(valueInfo.searchValue).then(res => {
                console.log(res);
                // 置空
                valueInfo.options = [];
                let idx = 0;
                // albums_length 专辑数量
                let albums = res.data.result.albums || [];
                let artists = res.data.result.artists || [];
                let playlists = res.data.result.playlists || [];
                let songs = res.data.result.songs || [];
                // 搜索建议专辑
                for (let item of albums) {
                    let tmp = {};
                    tmp.label = '专辑-' + item.name;
                    tmp.key = item.id;
                    valueInfo.options[idx] = tmp;
                    idx++;
                }
                // 搜索建议歌手
                for (let item of artists) {
                    let tmp = {};
                    tmp.label = '歌手-' + item.name;
                    tmp.key = item.id;
                    valueInfo.options[idx] = tmp;
                    idx++;
                }
                // 搜索建议歌单
                for (let item of playlists) {
                    let tmp = {};
                    tmp.label = '歌单-' + item.name;
                    tmp.key = item.id;
                    valueInfo.options[idx] = tmp;
                    idx++;
                }
                // 搜索建议歌单
                for (let item of songs) {
                    let tmp = {};
                    tmp.label = '歌曲-' + item.name + '-' + item.artists[0].name;
                    tmp.key = item.id;
                    valueInfo.options[idx] = tmp;
                    idx++;
                }
            })
        }
        
        const handleSelect = (key, object) => {
            let labelSplitArr = object.label.split('-');
            valueInfo.searchValue = labelSplitArr[1];
            let id = key;
            let ids = key;
            if (labelSplitArr[0] === '歌手') {
                if (id === 0) {
                    notification['error']({
                        content: '获取到的资源id错误',
                        meta: '切勿重复点击'
                    })
                } else {
                    router.push({path: '/artist', query: {id}});
                }
            } else if (labelSplitArr[0] === '专辑') {
                if (id === 0) {
                    notification['error']({
                        content: '获取到的资源id错误',
                        meta: '切勿重复点击'
                    })
                } else {
                    router.push({path: '/album', query: {id}});
                }
            } else if (labelSplitArr[0] === '歌单') {
                if (id === 0) {
                    notification['error']({
                        content: '获取到的资源id错误',
                        meta: '切勿重复点击'
                    })
                } else {
                    router.push({path: '/playlist', query: {id}});
                }
            } else if (labelSplitArr[0] === '歌曲') {
                if (ids === 0) {
                    notification['error']({
                        content: '获取到的资源id错误',
                        meta: '切勿重复点击'
                    })
                } else {
                    router.push({path: '/song', query: {ids}});
                }
            }
        }
        
        // 标签页切换事件
        const onUpdateTabs = (value) => {
            if (value === pageInfo.currentTabName) {
                return null;
            }
            pageInfo.currentTabName = value;
            pageInfo.page = 1;
            if (value === '歌曲') {
                init();
            } else if (value === '歌手') {
                getSearchValue(valueInfo.searchValue, 100).then(res => {
                    pageInfo.pageItem['歌手'] = res.data.result.artistCount;
                    pageInfo.pageCount = calInteger(res.data.result.artistCount / valueInfo.pageLimit);
                    valueInfo.artists = res.data.result.artists;
                })
            } else if (value === '专辑') {
                getSearchValue(valueInfo.searchValue, 10).then(res => {
                    pageInfo.pageItem['专辑'] = res.data.result.albumCount;
                    pageInfo.pageCount = calInteger(res.data.result.albumCount / valueInfo.pageLimit);
                    valueInfo.albums = res.data.result.albums;
                })
            } else if (value === 'MV') {
                getSearchValue(valueInfo.searchValue, 1004).then(res => {
                    pageInfo.pageItem['MV'] = res.data.result.mvCount;
                    pageInfo.pageCount = calInteger(res.data.result.mvCount / valueInfo.pageLimit);
                    valueInfo.mvs = res.data.result.mvs;
                })
            } else if (value === 'video') {
                getSearchValue(valueInfo.searchValue, 1014).then(res => {
                    console.log(res);
                    pageInfo.pageItem['video'] = res.data.result.videoCount;
                    pageInfo.pageCount = calInteger(res.data.result.videoCount / valueInfo.pageLimit);
                    valueInfo.videos = res.data.result.videos;
                })
            } else if (value === '歌单') {
                getSearchValue(valueInfo.searchValue, 1000).then(res => {
                    console.log(res);
                    pageInfo.pageItem['歌单'] = res.data.result.playlistCount;
                    pageInfo.pageCount = calInteger(res.data.result.playlistCount / valueInfo.pageLimit);
                    valueInfo.playlists = res.data.result.playlists;
                })
            } else if (value === '用户') {
                getSearchValue(valueInfo.searchValue, 1002).then(res => {
                    console.log(res);
                    pageInfo.pageItem['用户'] = res.data.result.userprofileCount;
                    pageInfo.pageCount = calInteger(res.data.result.userprofileCount / valueInfo.pageLimit);
                    valueInfo.userProfiles = res.data.result.userprofiles;
                })
            }
            beLoading();
        }
        // 关注用户时间
        const followedUser = (index, userId, flag) => {
            // 关注
            if (flag === 1) {
                valueInfo.userProfiles[index].followed = true;
            } else {
                // 取消关注
                valueInfo.userProfiles[index].followed = false;
            }
        }
        
        // 播放按钮hover效果
        const isShowPlayIconBacg = (index, color) => {
            valueInfo.playIconColor[index] = color;
        }
        
        // 根据ＩＤ获取专辑详情
        const getRouterToAlbumList = (id) => {
            if (id === 0) {
                notification['error']({
                    content: '获取到的用户id错误',
                    meta: '切勿重复点击'
                })
            } else {
                router.push({path: '/album', query: {id}});
            }
        }
        // 跳转到歌手详情页面
        const getRouterToArtistInfo = (id) => {
            if (id === 0) {
                notification['error']({
                    content: '获取到的用户id错误',
                    meta: '切勿重复点击'
                })
            } else {
                router.push({path: '/artist', query: {id}});
            }
        }
        // 跳转到歌曲详情页面
        const songDetailPage = (ids) => {
            if (ids === 0) {
                notification['error']({
                    content: '获取到的用户id错误',
                    meta: '切勿重复点击'
                })
            } else {
                router.push({path: '/song', query: {ids}});
            }
        }
        // 根据ＩＤ获取歌单详情
        const getListDetail = (id) => {
            if (id === 0) {
                notification['error']({
                    content: '获取到的用户id错误',
                    meta: '切勿重复点击'
                })
            } else {
                router.push({path: '/playlist', query: {id}});
            }
        }
        // 跳转到用户主页
        const getRouterToUserHome = (id) => {
            if (id === 0) {
                notification['error']({
                    content: '获取到的用户id错误',
                    meta: '切勿重复点击'
                })
            } else {
                router.push({path: '/user/home', query: {id}});
            }
        }
        // 跳转到搜索页面
        const getRouterToSearchValue = (keywords) => {
            if (keywords.length === 0) {
                notification['warning']({
                    content: '搜索内容为空',
                    meta: '请输入搜索关键字'
                })
            } else {
                router.push({path: '/search', query: {keywords}});
            }
        }
        
        const getRouterToVideoPage = (item) => {
            console.log(item);
            if (typeof item.vid === 'undefined') {
                // 类型是MV
                router.push({path: '/video', query: {id: item.id, type: 1}});
            } else {
                // 类型是视频
                router.push({path: '/video', query: {id: item.vid, type: 5}});
            }
        }
        
        return {
            ...toRefs(valueInfo),
            ...toRefs(pageInfo),
            route,
            inputChange,
            handleSelect,
            onUpdateTabs,
            isShowPlayIconBacg,
            calMSToMinAndS,
            calString,
            getRouterToAlbumList,
            getRouterToArtistInfo,
            songDetailPage,
            musicPlay,
            OnPageUpdate,
            calData,
            getListDetail,
            getRouterToUserHome,
            followedUser,
            getRouterToSearchValue,
            getRouterToVideoPage
        }
    },
    components: {
        NDropdown,
        NInput,
        NCard,
        NTabs,
        NTabPane,
        NPagination,
        NIcon,
        NImage,
        NButton
    }
}
</script>

<style scoped lang="scss">
@import '@/assets/css/base.scss';

.search-value-box {
    width: $client-width;
    background: #f4f4f4;
    
    
    .sv-t {
        @apply flex items-center justify-center;
        min-height: 150px;
        
        .search-input {
            @apply border-2 border-gray-300 border-transparent focus:outline-none
            focus:ring-2 focus:ring-gray-300 focus:border-transparent rounded-l-xl h-10 w-96 shadow cursor-text;
            font-size: 12px;
            color: #333;
            font-family: Arial, Helvetica, sans-serif;
            text-indent: 1rem;
            -webkit-text-size-adjust: none;
        }
        
        .search-icon {
            @apply h-10 w-12 flex items-center justify-center border-2 border-gray-300 border-transparent focus:outline-none
            focus:ring-2 focus:ring-gray-300 focus:border-transparent;
        }
    }
    
    .sv-content {
        @apply mx-16;
        
        min-height: $client-height;
    }
}
</style>